<?php

/*
 * 
 * 苏州活动的控制器
 * 
 * 1. 查看活动参与者排名列表【分页】
 * 
 * 2. 投票
 * 
 * 3. 投票用户的是否粉丝的判断
 * 
 * 4. 分享查看页面
 * 
 * 
 * 
 */


namespace M\Controller;
use Think\Controller;
class AcsuzhouController extends CommonController {
    
    /*
     * 
     * #################### 3 食品安全小卫士 ##################
     * 
     * 
     * 
     * 
     */
    
    /*
    * 
    * 苏州活动的控制器
    * 
    * 1. 查看活动参与者排名列表【分页】
    * 
    * 2. 投票
    * 
    * 3. 投票用户的是否粉丝的判断
    * 
    * 4. 分享查看页面
    * 
    * 
    * 
    */
   
    //小卫士排行
    public function xws_rank() {
        
        /*
        * 访问量要增加
        */
        $this->_add_view_count();
        
        /*
         * 要过滤出来
         * 去投票的这个人的所在学校和班级
         * 
         *
         */
        
        $id = I("get.id");
        $this->assign('id', $id);
        
        $res_filter = M("acsuzhou_xws_vote")->find($id);
        
        /*
         * 1. 班级排名
         * 2. 学校排名
         * 
         */
        $type= I("get.type");
        
        
        
        

      if(IS_GET){

        $DB_1 = M('acsuzhou_xws_vote');
        $DB_2 = M('acsuzhou_xws_vote_log');
        $member_num = $DB_1->count();
        $vote_num = $DB_2->count();
        $search_keywords = I('get.search_keywords');
        if(!empty($search_keywords)){

            if(is_numeric($search_keywords)){

            $sql = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
               fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid where 
               fd_acsuzhou_xws_vote.id=".$search_keywords." and fd_acsuzhou_xws_vote.class_id=".$res_filter['class_id']." and fd_acsuzhou_xws_vote.schoolid=".$res_filter['schoolid']." and fd_acsuzhou_xws_vote.grade_id=".$res_filter['grade_id'];
            }else{
               $sql = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
                   fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid where 
                   fd_acsuzhou_member_info.name like '%".$search_keywords."%'"." and fd_acsuzhou_xws_vote.class_id=".$res_filter['class_id']." and fd_acsuzhou_xws_vote.schoolid=".$res_filter['schoolid']." and fd_acsuzhou_xws_vote.grade_id=".$res_filter['grade_id'];
            }
            $list = $DB_1->query($sql);
            foreach ($list as $key => $value) {
              # code...
              $map['vote_num'] = array('egt',$value['vote_num']);
              $list[$key]['rank'] = $DB_1->where($map)->count();
            }
            // print_r($list); die;
        }else{
            /**
            数据分页显示开始
            **/
            if($type==1)
            {
                $sql1 = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
                   fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid"." where  fd_acsuzhou_xws_vote.schoolid=".$res_filter['schoolid']." order by fd_acsuzhou_xws_vote.vote_num desc";
            }
            else
            {
                $sql1 = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
                   fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid"." where fd_acsuzhou_xws_vote.class_id=".$res_filter['class_id']." and fd_acsuzhou_xws_vote.schoolid=".$res_filter['schoolid']." and fd_acsuzhou_xws_vote.grade_id=".$res_filter['grade_id']." order by fd_acsuzhou_xws_vote.vote_num desc";
            }
            
                   
            $list1 = $DB_1->query($sql1);
            
            $count      = count($list1);// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            if($type==1)
            {
                $sql = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
                   fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid"." where fd_acsuzhou_xws_vote.schoolid=".$res_filter['schoolid']." order by fd_acsuzhou_xws_vote.vote_num desc".
                   " limit ".$Page->firstRow.",".$Page->listRows;
            }
            else
            {
                $sql = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
                   fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid"." where fd_acsuzhou_xws_vote.class_id=".$res_filter['class_id']." and fd_acsuzhou_xws_vote.schoolid=".$res_filter['schoolid']." and fd_acsuzhou_xws_vote.grade_id=".$res_filter['grade_id']." order by fd_acsuzhou_xws_vote.vote_num desc".
                   " limit ".$Page->firstRow.",".$Page->listRows;
            }
            
            $list = $DB_1->query($sql);
            // echo $DB_1->getLastSql(); die;
            /**
            数据分页结束
            **/
            $page_count = ($Page->firstRow)/10; 
            foreach ($list as $key => $value) {
              # code...
              // $list[$key]['vote_num'] = $DB_2->where(array('wsid' => $value['id']))->count();
              $list[$key]['rank'] = $page_count *  10 + $key + 1;
            }
        }

        // print_r($list); die;
        /**
         * 访问量获取
         */
        $xws_pv = M('vote_setting')->where(array('keyword' => 'xws_pv'))->getField('keyvalue');

        $this->assign('xws_pv',$xws_pv);
        $this->assign('member_num',$member_num);
        $this->assign('vote_num',$vote_num);
        $this->assign('show',$show);
        $this->assign('list',$list);
        
        $statistics_data = $this->_get_statistics_data();
        $this->assign("statistics_data", $statistics_data);
        
        $this->display();
      }
    }

    //详情
    public function xws_vote_detail() {
        /*
        * 访问量要增加
        */
        $this->_add_view_count();
        
        if(IS_GET){

            $id = I('get.id');
            $DB_1 = M('acsuzhou_xws_vote');
            // $DB_2 = M('acsuzhou_xws_vote_log');
            $sql = "select fd_acsuzhou_xws_vote.*,fd_acsuzhou_member_info.name as name from fd_acsuzhou_xws_vote left join
               fd_acsuzhou_member_info on fd_acsuzhou_xws_vote.mid=fd_acsuzhou_member_info.mid where 
               fd_acsuzhou_xws_vote.id=".$id;
            $list = $DB_1->query($sql);

            // print_r($list); die;
            $this->assign('list',$list);
            $statistics_data = $this->_get_statistics_data();
            $this->assign("statistics_data", $statistics_data);
            $this->display();
        }
    }
   
   //小卫士投票
    public function xws_vote_it() {
       /*vote_it
        * ##Rule: 一人一天只能投票一次
        * 
        */  
      if(IS_AJAX){

        $mid = $this->memberinfo['id'];
        $id = I('post.id');
        $isfan = $this->_chk_if_fan($mid);

        if($isfan){
            //判断用户是否已投过票
            $re = $this->_chk_is_vote($mid);
            // echo $re; die;
            if($re){
              //已投票
//              echo json_encode(2);
              echo 2;
            }else{
                $data['wsid'] = $id;
                $data['openid'] = M('members')->where(array('id' => $mid))->getField('wxopenid');
                $data['ctime'] = I('server.REQUEST_TIME');

                M('acsuzhou_xws_vote_log')->data($data)->add();
                $result = M('acsuzhou_xws_vote')->where("id=".$id)->setInc('vote_num',1);
                if(!empty($result)){
                    echo 1;
//                  echo json_encode(1);
                }
            }
        }else{
            
          //未关注
//          echo json_encode(3);
          echo 3;
        }
      }
       
   }
   
   /*
    * 判断是否是粉丝
    */
   private function _chk_if_fan($mid) {
       //根据 mid 获取到 Unionid
       //然后判断 unionid 是否是 两个微信号的粉丝
      $openid = M('members')->where(array('id' => $mid))->getField('wxopenid');
      // echo $openid; die;
      $DB = M("members_subscribe_records");
      $map['openid'] = $openid;
      $map['issubscribe']=1;
      $res = $DB->where($map)->find();
      return $res;
   }

   /**
    * 检查是否投过票
    */
   private function _chk_is_vote($mid){

//      $openid = M('members')->where(array('id' => $mid))->getField('wxopenid');
//
//      $DB = M('acsuzhou_xws_vote_log');
//      $map['openid'] = $openid;
//      $todaytime = strtotime(date('Y-m-d',time()));
//      $map['ctime'] = array('gt',$todaytime);
//      $res = $DB->where($map)->find();
//      // echo $DB->getLastSql(); die;
//      return $res;
      
      /*
        * 先判断是否为自己投给自己
        */
       
       $res_vote_info = M("acsuzhou_xws_vote")->find($id);
       
       if($res_vote_info['mid']==$mid)
       {
           return TRUE;
       }
       else
       {
           $openid = M('members')->where(array('id' => $mid))->getField('wxopenid');

            $DB = M('acsuzhou_xws_vote_log');
            $map['openid'] = $openid;
            $todaytime = strtotime(date('Y-m-d',time()));
            $map['ctime'] = array('gt',$todaytime);
            $res = $DB->where($map)->find();
            return $res;
       }
   }
   
   /**
    * ajax增加访问量
    * 
    */
   public function add_pv_xws(){
      if(IS_AJAX){
          $DB = M('vote_setting');
          $re = $DB->where(array('keyword' => 'xws_pv'))->setInc('keyvalue',1);
          if($re){
              echo 1;
          }
      }
   }











   /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
   
   
   /*
    * ################## 你投票我检查活动 ##################
    */
   
   
   /*
    * 投票列表
    */
   
   public function like_product_list() {

       if(IS_GET){

          $DB = M('acsuzhou_product');
          $DB_log = M('acsuzhou_vote_log');
          /**
            数据分页显示开始
            **/
          $map_1['ishidden']=0;
          $map_1['type']=0;
          $map_1['vote_num']=array("LT",300);
          
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acsuzhou_product.* from fd_acsuzhou_product where ishidden=0 and type=0 and vote_num <300 order by vote_num desc"." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
          $page_count = ($Page->firstRow)/10;
          foreach ($list as $key => $value) {
            # code...
            // $list[$key]['vote_num'] = $DB_log->where(array('pid' => $value['id']))->count();
            $list[$key]['rank'] = $page_count * 10 + $key + 1;
          }
          /**
           * 循环判断用户是否投票过
           */
          $todaytime = strtotime(date('Y-m-d',time()));
          $map['ctime'] = array('gt',$todaytime);
          $map['mid'] = $this->memberinfo['id'];
          // $map['mid'] = 11;
          foreach ($list as $key => $value) {
            # code...
            $map['pid'] = $value['id'];

            $re = $DB_log->where($map)->find();
            if($re){
              $list[$key]['is_vote'] = 1;
            }else{
              $list[$key]['is_vote'] = 0;
            }
          }
          // print_r($list); die;
          $this->assign('list',$list);

          $this->display();
       }
   }
   
   /*
    * 送检产品列表
    */
   public function like_product_success_list() {
      if(IS_GET){

          $DB = M('acsuzhou_product');
          $map_1['ishidden']=0;
          $map_1['type']=0;
          $map_1['vote_num']=array("EGT",300);
          /**
            数据分页显示开始
            **/
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acsuzhou_product.* from fd_acsuzhou_product where ishidden=0 and type=1 and vote_num >=300 "." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
            // print_r($list); die;
            $this->assign('page',$show);// 赋值分页输出
            $this->assign('list',$list);
            $this->display();
      }
   }
   
   
   /*
    * 上传产品
    */
   public function like_product_diy_submit() {
      $this->display(); 
       
   }
   
   
   /*
    * 活动说明 
    */
   public function like_notice() {
       $this->display();
   }
   
   
   /**
    * ajax投票 每个用户每个项目只投一票
    */
   public function add_one_vote(){
      if(IS_AJAX){

          $DB = M('acsuzhou_vote_log');
          $pid = I('post.pid');
          $mid = $this->memberinfo['mid'];
          // $mid = 11;
          $ctime = I('server.REQUEST_TIME');
          $DB->data(array('pid' => $pid,'mid' => $mid,'ctime' => $ctime))->add();
          $re = M('acsuzhou_product')->where(array('id' => $pid))->setInc('vote_num',1);
          if(!empty($re)){
              echo 1;
          }
      }
   }
   
   /*
    * 访问量要增加
    */
   private function _add_view_count()
   {
       M("vote_setting")->where("id=2")->setInc("keyvalue");
   }
   
   /*
     * 计算
     * * 参与人数
        * 投票数量
        * 浏览数量
     */
    private function _get_statistics_data()
    {
        $data['join_count']= M("acsuzhou_xws_vote")->count();
        $data['vote_count']=M("acsuzhou_xws_vote_log")->count();
        $data['view_count'] = M("vote_setting")->where(array('keyword'=>'sz_xws_pv'))->getField('keyvalue');
        
        return $data;
    }

   /**
    * 查询用户是否已经给该项目投过票
    */
   
   /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
   







   /**
      你投票我检测app页面
   **/
   
   /*
    * 投票列表
    */
   
   public function like_product_list_app() {

       if(IS_GET){

          $DB = M('acsuzhou_product');
          $DB_log = M('acsuzhou_vote_log');
          
          $map_1['ishidden']=0;
          $map_1['type']=0;
          $map_1['vote_num']=array("LT",300);
          /**
            数据分页显示开始
            **/
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acsuzhou_product.* from fd_acsuzhou_product where ishidden=0 and type=0 and vote_num <300 order by vote_num desc"." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
          $page_count = ($Page->firstRow)/10;
          foreach ($list as $key => $value) {
            # code...
            // $list[$key]['vote_num'] = $DB_log->where(array('pid' => $value['id']))->count();
            $list[$key]['rank'] = $page_count * 10 + $key + 1;
          }
          /**
           * 循环判断用户是否投票过
           */
          $todaytime = strtotime(date('Y-m-d',time()));
          $map['ctime'] = array('gt',$todaytime);
          // $map['mid'] = $this->memberinfo['id'];
          $map['mid'] = I('get.mid');
          foreach ($list as $key => $value) {
            # code...
            $map['pid'] = $value['id'];

            $re = $DB_log->where($map)->find();
            if($re){
              $list[$key]['is_vote'] = 1;
            }else{
              $list[$key]['is_vote'] = 0;
            }
          }
          // print_r($list);die;
          $this->assign('page',$show);// 赋值分页输出
          $this->assign('list',$list);
          $this->assign('mid',$map['mid']);
          $this->display();
       }
   }
   
   /*
    * 送检产品列表
    */
   public function like_product_success_list_app() {
      if(IS_GET){

          $DB = M('acsuzhou_product');
          $mid = I('get.mid');
          
           $map_1['ishidden']=0;
          $map_1['type']=1;
          $map_1['vote_num']=array("EGT",300);
          /**
            数据分页显示开始
            **/
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acsuzhou_product.* from fd_acsuzhou_product where ishidden=0 and type=1 and vote_num >= 300 "." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
            // print_r($list); die;
            $this->assign('list',$list);
            $this->assign('mid',$mid);
            $this->display();
      }
   }
   
   
   /*
    * 上传产品
    */
   public function like_product_diy_submit_app() {
    
    if(IS_POST)
    {
        
        if(!empty($_FILES['image']['tmp_name']))
        {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     31457280 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =      'Public/'; // 设置附件上传目录
            $upload->savePath  =      'uploads/'; // 设置附件上传目录
            // 上传文件 
            $info   =   $upload->uploadOne($_FILES['image']);

            if(!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } 
            
            $data['img']="/".$upload->rootPath.$info['savepath'].$info['savename'];
            $thumb = $this->img_thumb2($data['img']);
            $data['img'] = $thumb;
            
        }

        $data['name']=I("post.productname");
        
        $data['ctime']=I("server.REQUEST_TIME");
        $data['mid']= I("post.mid");
        
        $id = M("acsuzhou_product")->add($data);
        
        if($id)
        {
            redirect(U('like_product_list_app',array('mid'=>I("post.mid"))));
        }
        else {
           
        }
        
        
    }
    else
    {
         $mid = I('get.mid');
         $this->assign('mid',$mid);
         $this->display();  
    }
     
       
   }
   
   private function img_thumb2($img_url)
	{
		$image = new \Think\Image(); 
		$img_url = './'.$img_url;
		$image->open("$img_url");
		$img_name=$this->img_name().'.jpg';
		$re_small_url=__ROOT__.'/'.'Uploads'.'/'.'adv'.'/'.'change_small'.'/'.$img_name;
		$small_url='./'.'Uploads'.'/'.'adv'.'/'.'change_small'.'/'.$img_name;
		// echo $small_url; die;
		// 生成一个居中裁剪为30*30的缩略图并保存
		$image->thumb(500, 500,\Think\Image::IMAGE_THUMB_SCALE)->save($small_url);
		return $re_small_url;
	}
        
        //生成随机图像名称
	private function img_name()
	{
		$time=I('server.REQUEST_TIME');
		return $time.str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	}
   
   
   /*
    * 活动说明 
    */
   public function like_notice_app() {

      $mid = I('get.mid');
      $this->assign('mid',$mid);
      $this->display();
   }
   
   
   /**
    * ajax投票 每个用户每个项目只投一票
    */
   public function add_one_vote_app(){
      if(IS_AJAX){

          $DB = M('acsuzhou_vote_log');
          $pid = I('post.pid');
          // $mid = $this->memberinfo['mid'];
          $mid = I('post.mid');
          $ctime = I('server.REQUEST_TIME');
          $map['pid'] = $pid;
          $map['mid'] = $mid;
          $todaytime = strtotime(date('Y-m-d',time()));
          $map['ctime'] = array('gt',$todaytime);
          $is_vote = $DB->where($map)->find();
          //如果已经投过票
          if($is_vote){

              $re = 0;
          }else{

              $DB->data(array('pid' => $pid,'mid' => $mid,'ctime' => $ctime))->add();
              $re = M('acsuzhou_product')->where(array('id' => $pid))->setInc('vote_num',1);
          }
          /*
           * 判断是否满标了
           */
          $db_2 = M('acsuzhou_product');
          $res = M('acsuzhou_product')->find($pid);
          if($res['vote_num']>=300)
          {
              $db_2->id = $pid;
              $db_2->type=1;
              $db_2->save();
              print_r($res);
          }
          
          if(!empty($re)){
            
              echo 1;
          }else{

              echo 0;
          }
      }
   }
   
   /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
    


    /**
    考试开始
    **/



    /**
     * 考试报名
     */
    public function exam_enter_for(){

      if(IS_GET){

        $DB = M('acsuzhou_member_info');
        $mid = $this->memberinfo['id'];
        $res = $DB->where(array('mid' => $mid,'is_exam' => 1))->find();
        if($res){

            $this->redirect('M/acsuzhou/exam_result');
        }else{

            $schoolid = I('get.schoolid');
            $school_name = M('acsuzhou_school')->where(array('id' => $schoolid))->getField('name');
            $avatar = M('members')->where(array('id' => $mid))->getField('avatar');
            // $mid = 11;
            $re = $DB->where(array('mid' => $mid))->find();
        }
        
        if($re){



            $this->assign('avatar',$avatar);
            $this->assign('schoolid',$schoolid);
            $this->assign('school_name',$school_name);
            $this->assign('name',$re['name']);
            $this->assign('grade_id',$re['grade_id']);
            $this->assign('class_id',$re['class_id']);
            $this->assign('grade',$re['grade']);
            $this->assign('class',$re['class']);
            $this->display();

        }else{
            $this->assign('avatar',$avatar);
            $this->assign('schoolid',$schoolid);
            $this->assign('school_name',$school_name);
            $this->display();
        }
        
      }else if(IS_POST){

        $data['mid'] = $this->memberinfo['id'];
        // $data['mid'] = 11;
        $data['school'] = trim(I('post.school'));
        $data['schoolid'] = I('post.schoolid');
        $data['grade'] = I('post.grade');
        $data['grade_id'] = I('post.grade_id');
        $data['class'] = I('post.class');
        $data['class_id'] = I('post.class_id');
        $data['name'] = trim(I('post.name'));
        $DB = M('acsuzhou_member_info');

        $is_modify = $DB->where(array('mid' => $data['mid']))->find();
        if(empty($is_modify)){
            
            $re = $DB->data($data)->add();
        }else{
            // print_r($data);die;
            $re = $DB->where(array('id' => $is_modify['id']))->data($data)->save();
            // var_dump($re); die;
        }

        
        if(!empty($re)){

          $this->redirect('M/acsuzhou/exam_answers');
        }else{

          $this->redirect('M/acsuzhou/exam_answers');
        }
      }
    }



    /**
     * 学习知识
     */
    public function exam_learn(){

      if(IS_GET){
        $schoolid = I('get.schoolid');
        $DB = M('acsuzhou_item_pool');
        $sql = 'select * from fd_acsuzhou_item_pool';
        $list = $DB->query($sql);

        foreach ($list as $key => $value) {
          # code...
          $res['questions'][$key]['question'] = $value['title'];
          $res['questions'][$key]['answers'][] = $value['optionA'];
          $res['questions'][$key]['answers'][] = $value['optionB'];
          $res['questions'][$key]['answers'][] = $value['optionC'];
          $res['questions'][$key]['answers'][] = $value['optionD'];
          $res['questions'][$key]['correctAnswer'] = $value['right_option'];
        }
        $res = json_encode($res);
        
        $this->assign('schoolid',$schoolid);
        $this->assign('res',$res);
        $this->display();
      }
    }



    /**
     * 开始考试
     */
    public function exam_answers(){
      $mid = $this->memberinfo['id'];
      // $mid = 11;
      $re = $this->check_member_isexam($mid);

      if($re){

          $this->redirect('M/acsuzhou/exam_result');

      }else{

          $DB = M('acsuzhou_item_pool');
          $sql = 'select * from fd_acsuzhou_item_pool order by rand() limit 20';
          $list = $DB->query($sql);

          foreach ($list as $key => $value) {
            # code...
            $res['questions'][$key]['question'] = $value['title'];
            $res['questions'][$key]['answers'][] = $value['optionA'];
            $res['questions'][$key]['answers'][] = $value['optionB'];
            $res['questions'][$key]['answers'][] = $value['optionC'];
            $res['questions'][$key]['answers'][] = $value['optionD'];
            $res['questions'][$key]['correctAnswer'] = $value['right_option'];
          }
          $res = json_encode($res);
          $this->assign('res',$res);
          $this->display();
      }
    }

    /**
     * 当考试结束后将用户的考试状态修改为已考试
     */
    public function modify_member_isexam(){
      if(IS_AJAX){

        $mid = $this->memberinfo['id'];
        // $mid = 11;
        $re = M('acsuzhou_member_info')->where(array('mid' => $mid))->data(array('is_exam' => 1))->save();
        if($re){
          echo 1;
        }
      }
    }


    /**
     * 考试结果
     */
    public function exam_result(){

      if(IS_GET){
        
        $DB = M('acsuzhou_member_info');
        $mid = $this->memberinfo['id'];
        // $mid = 11;
        $sql = "select fd_acsuzhou_member_info.name,fd_acsuzhou_member_info.school,fd_members.avatar from fd_acsuzhou_member_info 
        left join fd_members on fd_acsuzhou_member_info.mid=fd_members.id where fd_acsuzhou_member_info.mid=".$mid;
        $list = $DB->query($sql);

        $this->assign('list',$list);
        $this->assign('mid', $mid);
        
        $this->display();
      }
    }


    /**
     * 检测用户是否考试过
     */
    private function check_member_isexam($mid){
      $map['mid'] = $mid;
      $map['is_exam'] = 1;
      $DB = M('acsuzhou_member_info');

      $re = $DB->where($map)->find();
      return $re;
    }
    
    
    /*
     * 参加抽奖说明页面
     */
    public function instruction_choujiang() {
        $this->display();
    }
    
    /*
     * 参加抽奖说明页面
     */
    public function instruction_pingxuan() {
        $this->display();
    }
    
    
    /*
     * 参加抽奖说明页面
     */
    public function instruction_vote() {
        $this->display();
    }
    
    
    


    /**
    考试结束
    **/
    
    
    
    /*
     * 摇一摇抽奖
     * 
     * 获取中奖的资料
     * 判断是否有中奖
     * 
     */
    public function prize_yaoyiyao() {
        
        $mid = $this->memberinfo['id'];
        
        $DB = M("acsuzhou_member_info");
        $map['mid']=$mid;
        $res=  $DB->where($map)->find();
        
        if(!empty($res))
        {
            //有记录
            $this->assign('lefttime', $res['prize_left_count']);
        }
        else
        {
            //没有记录
            $this->assign('lefttime', 0);
        }
        
        $this->assign("mid", $mid);
        $this->display();
    }
    
    
    /*
     * 
     * 中奖结果
     */
    public function prize_result() {
         //判断环境
        if(!C('debug'))
        {
            $site_domain = C('product_domain');
        }
        else
        {
            $site_domain = C('development_domain');
        }
        
        $mid = $this->memberinfo['id'];
        
        $map['mid']=$mid;
        $map['pid']=array("gt",0);
        $DB = M("acsuzhou_prize_record");
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
//            有获奖记录
            $prize_content = M("acsuzhou_prize_repository")->find($res['pid']);
            $data['prize_thumb'] = $site_domain.$prize_content['img'];
            $data['is_prize']=1;
            
        }
        else
        {
//            没有获奖
            $data['prize_thumb'] = $site_domain.'/Public/acsuzhou/images/win.png';
            $data['is_prize']=0;
            
        }
        
        $this->assign('result', $data);
        
        $this->display();
    }
    
    /*
     * 计算是否中奖
     * 
     * 通过提交来的 mid 来计算中奖的情况
     */
    public function get_prize() {
        //判断环境
        if(!C('debug'))
        {
            $site_domain = C('product_domain');
        }
        else
        {
            $site_domain = C('development_domain');
        }
        
        $mid = $this->memberinfo['id'];
        
        
            /*
             * 获取个人资料，得到是几年级的学生，查看相同班级的同学，礼品数量是否兑换完了
             *              1. 已经换完，就提示没中奖，减掉次数
             *              2. 没有换完，计算中的概率，看结果
             * 减去中奖次数
             */
            
            $DB_member_info = M("acsuzhou_member_info");
            $member_info = $DB_member_info->where(array('mid'=>$mid))->find();
            
            
            if($member_info['is_prize']==1)
            {
                //中奖过的情况，直接提示不中奖了
                $result['is_prize']=0;
                $result['prize_msg']="没中奖1";
                if($member_info['prize_left_count']>0)
                {
                    $result['prize_left_count']=$member_info['prize_left_count']-1;
                    $this->_reduce_prize_count($mid);
                    
                    //增加不中奖的记录
                        $this->_add_unwin_prize_record($member_info);
                }
                else
                {
                    $result['prize_left_count']=0;
                }
                
                $this->json_output($result);  
                exit();
                
            }
            
            
            if($member_info['prize_left_count']==0)
            {
                // 没抽奖的次数的情况
                $result['is_prize']=0;
                $result['prize_msg']="没中奖2";
                $result['prize_left_count']=0;
            }
            else
            {
                //还有抽奖次数的情况
                $randmom = rand(0,1);
                if($randmom==1)
                {
                    //几率中奖，还要判断是否还剩余奖品
                    $DB_prize_record = M("acsuzhou_prize_record");
                    $map_prize_record['schoolid']=$member_info['schoolid'];
                    $map_prize_record['grade_id']=$member_info['grade_id'];
                    $map_prize_record['class_id']=$member_info['class_id'];
                    $map_prize_record['pid']=array("gt",0);
                    
                    $res_prize_record = $DB_prize_record->where($map_prize_record)->select();
                    
                    if(!empty($res_prize_record))
                    {
                        $tmp_prize_got = "(";
                        foreach ($res_prize_record as $key => $value) {
    //                        array_push($tmp_prize_got, $value['pid']);
                            $tmp_prize_got .=$value['pid'].",";
                        }
                        $tmp_prize_got = substr($tmp_prize_got, 0,-1);
                        $tmp_prize_got .=")";
                    }
                    
                    
                    $res_prize_record_count  = count($res_prize_record);
                    
                    if($res_prize_record_count<10)
                    {
//                        还有中奖的机会
                        
                        $DB_acsuzhou_prize = M("acsuzhou_prize");
//                        $map_acsuzhou_prize['grade_id'] = 
                            
                            /*
                             * 测试着，那个奖品的关联关系还是单独算
                             * 
                             * 找出现在中奖的奖品有什么
                             * 
                             * 
                             */
                        
                            $prize_current_map['grade_id']=$member_info['grade_id'];
                            
                            $prize_current_res = $DB_acsuzhou_prize->where($prize_current_map)->select();
                            
//                             echo $DB_acsuzhou_prize->getLastSql();
//                             echo "<br/>";
                             
                            $tmp_prize_parent=array();
                            
                            foreach ($prize_current_res as $key => $value) {
                                array_push($tmp_prize_parent, $value['id']);
                            }
                            
//                            print_r($tmp_prize_got);
                            
//                            print_r($tmp_prize_parent);
                            $map_prize_children['parent_id']=array("in",$tmp_prize_parent);
                            if(!empty($res_prize_record))
                            {
                                $map_prize_children['id']=array("exp","not in $tmp_prize_got");
                            }
                            
//                            $map_prize_children['_logic']="OR";
                            
                            
                            $res_prize_children = M("acsuzhou_prize_repository")->where($map_prize_children)->select();
//                            
//                            echo M("acsuzhou_prize_repository")->getLastSql();
//                            print_r($res_prize_children);
//                            
                            $current_get_prize = $res_prize_children[array_rand($res_prize_children,1)];
                            
//                            print_r($current_get_prize);
//                            
//                            exit();
                            
                            $result['is_prize']=1;
                            $result['prize_msg']="恭喜中奖1";
                            $result['prize_left_count']=$member_info['prize_left_count']-1;
                            $result['prize_thumb']=$site_domain.$current_get_prize['img'];
                            
                            
                            /*
                             * 写入中奖记录
                             */
                            $DB_data_get_prize = M("acsuzhou_prize_record");
                            $data_get_prize['mid']=$mid;
                            $data_get_prize['pid']=$current_get_prize['id'];
                            $data_get_prize['ctime']=I("server.REQUEST_TIME");
                            $data_get_prize['schoolid']=$member_info['schoolid'];
                            $data_get_prize['grade_id']=$member_info['grade_id'];
                            $data_get_prize['class_id']=$member_info['class_id'];
                            
                            $id_data_get_prize = $DB_data_get_prize->add($data_get_prize);
                            
                            if($id_data_get_prize)
                            {
                                $DB_member_info->id = $member_info['id'];
                                $DB_member_info->is_prize = 1;
                                $DB_member_info->save();  
                            }
                            
                            
                            
                            /*
                             * 测试着，那个奖品的关联关系还是单独算
                             */
                        
                        //抽奖次数减一
                        $this->_reduce_prize_count($mid);
                    }
                    else
                    {
//                        没有奖品了
                        $result['is_prize']=0;
                        $result['prize_msg']="没中奖3";
                        $result['prize_left_count']=$member_info['prize_left_count']-1;
                        
                        //抽奖次数减一
                        $this->_reduce_prize_count($mid);
                        
                        //增加不中奖的记录
                        $this->_add_unwin_prize_record($member_info);
                    }
                }
                else
                {
                    //没中奖，直接返回
                    $result['is_prize']=0;
                    $result['prize_msg']="没中奖4";
                    $result['prize_left_count']=$member_info['prize_left_count']-1;
                    
                    //抽奖次数减一
                        $this->_reduce_prize_count($mid);
                        
                        //增加不中奖的记录
                        $this->_add_unwin_prize_record($member_info);
                }
                
                
            }
            
          
            

            $this->json_output($result);  
        
    }
    
    
    /*
     * 减少抽奖的次数
     */
    private function _reduce_prize_count($mid)
    {
        M("acsuzhou_member_info")->where(array('mid'=>$mid))->setDec("prize_left_count");
    }
    
    /*
     * 增加不中奖的记录
     */
    private function _add_unwin_prize_record($member_info) {
        $data['mid']=$member_info['mid'];
        $data['pid']=0;
        $data['ctime']=I("server.REQUEST_TIME");
        $data['schoolid']=$member_info['schoolid'];
        $data['grade_id']=$member_info['grade_id'];
        $data['class_id']=$member_info['class_id'];
        
        M("acsuzhou_prize_record")->add($data);
        
        
    }
    
    
    /*
     * 统一输出的格式
     */
    public function json_output($data,$suc_msg="OK",$err_msg="NO",$more_data) {
        if(!empty($data))
        {
            $res['err']=0;
            $res['msg']=$suc_msg;
            $res['count']=count($data);

            $res['content']=$data;
            
            
            
        }
        else
        {
            $res['err']=0;
            $res['msg']=$err_msg;
            $res['count']=0;
            $res['content']="";
        }
        if(!empty($more_data))
        {
            $res['more_data']=$more_data;
        }
        
        echo json_encode($res);
    }

    
    
}
